package main

import (
	"flag"
	"fmt"
	"github.com/fatih/color"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"go-admin-server/app/dao"
	"go-admin-server/common/event"
	"go-admin-server/common/xlog"
	"go-admin-server/config"
	"go-admin-server/router"
)

var (
	webfs   = flag.String("webfs", "embed", "WEB资产, 可以是'embed'或者'osdir'")
	mailFS  = flag.String("mailfs", "embed", "邮件模板, 可以是'embed'或者'osdir'")
	cron    = flag.Bool("cron", true, "启动任务调度器")
	version = flag.Bool("version", false, "打印版本信息")
	addUser = flag.Bool("adduser", false, "添加第一个管理员")
)

// 从 -X 编译器选项获取
var Name, Version, BuildDate, BuildYear string

func init() {
	flag.Usage = func() {
		name := color.MagentaString(Name)
		fmt.Fprintf(flag.CommandLine.Output(), "%s %s(%s)", name, Version, BuildDate)
		fmt.Fprint(flag.CommandLine.Output(), "\n\n")
		flag.PrintDefaults()
	}

	// 设置 xlog
	xlog.Setup(true)
	xlog.X.Info("----------------- main init -----------------")
	dao.InitSqlite()
}

func main() {
	gin.SetMode(gin.ReleaseMode)

	// 解析命令行选项
	flag.Parse()

	logger := logrus.StandardLogger()
	logger.SetFormatter(&logrus.JSONFormatter{})
	logger.Info("this is INFO")
	logger.Error("this is error")
	logger.Warn("this is warn")
	logger.Debug("this is debug")

	_, err := config.Parse()
	if err != nil {
		logger.Fatalf("Failed to parse config: %v", err)
	}

	// 日志记录到事件表
	xlog.X.AddHook(event.NewEventHook(event.FormatJson))

	r := router.InitRouter(logger)
	err = r.Run(":8090")
	if err != nil {
		logger.Fatalf("start server failed: %v", err)
	}
}
